<template>
<div>
    <!--  面包屑-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>首页 </el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片 -->
<el-card>
    <el-row :gutter="20">
        <el-col :span="6">
    <el-input placeholder="请输入内容" v-model="queryInfo.query">
        <el-button slot="append" type="el-icon-search" @click="getUserList"></el-button>
    </el-input>
        </el-col>
        <el-col :span="4">
            <el-button type="primary">添加用户</el-button>
        </el-col>
    </el-row>
    <!-- 用户列表区域 -->
    <el-table
       border 
        stripe 
        :data="getList"
        style="width: 100%">
        <el-table-column
            type="index"
            label="#" >
        </el-table-column>
       <el-table-column
           label="姓名"
            prop="username">
       </el-table-column>
       <el-table-column
           label="邮箱"
            prop="email">
       </el-table-column>
       <el-table-column
           label="电话"
            prop="mobil">
       </el-table-column>
       <el-table-column
           label="状态"
            >
            <template slot-scope='scope'>
             <el-switch @change="userStateChange(scope.row)" v-model="scope.row.mg_state"></el-switch>
            </template>
       </el-table-column>
       <el-table-column label="操作" width="180px">
              <template slot-scope='scope'>
<el-button type="primary" @click="showEditDialog(scope.row.id)" icon="el-icon-edit"></el-button>
<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
<el-button type="warning" icon="el-icon-setting" ></el-button>
     </template>
       </el-table-column>
    </el-table>
   <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 5, 7, 20]"
      :page-size="1"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
</el-card>
<!-- 添加输入框 -->
<el-dialog
 @close="addDialogClosed"
  title="添加用户"
  :visible.sync="dialogVisible"
  width="50%"
  >
  <!-- 表单 -->
  <el-form ref="ruleFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
  <el-form-item label="添加用户" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
   <el-form-item label="添加用户"  prop="pwd">
    <el-input v-model="addForm.pwd"></el-input>
  </el-form-item>
   <el-form-item label="添加用户" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
   <el-form-item label="添加用户" prop="mobil">
    <el-input v-model="addForm.mobil"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改输入框 -->
<el-dialog
 @close="addDialogClosed"
  title="修改用户"
  :visible.sync="editDialogVisible"
  width="50%"
  @ close="editDialogClosed"
  >
  <!-- 表单 -->
  <el-form ref="editRuleFormRef" :model="editForm" :rules="addFormRules" label-width="70px">
  <el-form-item label="添加用户" prop="username">
    <el-input v-model="editForm.username" disabled></el-input>
  </el-form-item>
   <el-form-item label="添加用户"  prop="pwd">
    <el-input v-model="editForm.pwd"></el-input>
  </el-form-item>
   <el-form-item label="添加用户" prop="email">
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>
   <el-form-item label="添加用户" prop="mobil">
    <el-input v-model="editForm.mobil"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo" >确 定</el-button>
  </span>
</el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" >
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    </div>  
    
</template>

<script>
export default {
data() {
    return {

//         //校验邮箱的规则
//           checkEmail=(rule,value,callback)=>{
//             const reg_email= /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
//          if(reg_email.test(value)){
//              return callback()
//          }
//          callback(new Error('错误'))

// },
// //验证手机号码
//   checkMboil=(rule,value,callback)=>{
//             const reg_mobil=/^[1][3,4,5,7,8][0-9]{9}$/
//          if(reg_email.test(value)){
//              return callback()
//          }
//          callback(new Error('错误'))

// },
    
      dialogVisible :false,
      //控制修改对话框的显示与隐藏
      editDialogVisible:false,
      getList:[] ,
      total:0,
         queryInfo:{
             query:'',
             pagenum:1,
             pagesize:2
         },
         addForm:{
             username:'',
             pwd:'',
             email:'',
             mobil:''
         },
         editForm:{
             
         },
         addFormRules:{
             username:[
                 {required: true, message:'请输入用户名', trigger: 'blur'},
                 {require: true, min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
             ],
             pwd:[
                 {required: true, message:'请输入密码', trigger: 'blur'},
                 {require: true, min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
             ],email:[
                //  {required: true, message:'请输入邮箱', trigger: 'blur'},{
                //    validator:checkEmail,trigger:'blur'
                //  },
                 {require: true, min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
             ],
             mobil:[
                 {required: true, message:'请输入手机号', trigger: 'blur'},
                 {require: true, min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
                //  {validator:checkMboil,trigger:'blur'}
             ]
         },
          // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色Id值
      selectedRoleId: ''
    }
    
},
created() {
    this.getUserList()
},
methods :{
    //获取表格数据
    async getUserList(){
        const {data:res} =await this.$http('user',{params:this.queryInfo})
        if(res.data.status !==200)
        return this.$message('获取代码失败')
        this.getList=res.data.users
       this.total=res.data.total
    },
    //监听pagesize每页显示条数的事件
    handleSizeChange(newSize){
       this.queryInfo.pagesize=newSize
       this.getUserList()
    },
    //页码发生改变的时候
    handleCurrentChange(newPage){
      this.queryInfo.pagenum=newPage
      this.getUserList()
    },
    //监听swich的状态改变
    async userStateChange(userinfo){
      const {data:res}= await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
     if(res.mate.status!==200) {
          userinfo.mg_state=!userinfo.mg_state
         return this.$message.error('失败')
     }
      this.$message.success('更新成功')
    },
    //清空表单
    addDialogClosed(){
        this.$refs.addFormRef.resetFields()
    },
    //添加用户，调用接口
    addUser(){
        this.$refs.addFormRef.validate(async vaild=>{
            if(!vaild) return
            //发起添加请求
            const {data:res}= await this.$$http.post('users',this.addForm)
            if(res.mate.status!==201) return this.$message.error('错误')
             this.$message.success('成功')
             //关闭对话框
             this.dialogVisible=false
             this.getUserList()
        })
    },
    //修改订单
    async showEditDialog(id){
       this.editDialogVisible=true
      const {data:res}= await this.$$http.get('user/'+id)
      if(res.mate.status!==200){
            this.editForm= res.data
      }else{
          return this.$message.success('成功')
      }
    },
    //修改表单重置
     editDialogClosed(){
         this.$refs.editRuleFormRef.resetFields()
     },
     //修改数据
     editUserInfo(){
         this.$refs.editRuleFormRef.validate(async vaild=>{
             if(!vaild)return
             //发起修改请求
            const {data:res} = await this.$http.put('user/'+this.editForm.id,{emil:this.editForm.email,
                   mobil:this.editForm.mobil})

                   if(res.mate.status!==200)return this.$message.error('失败')
                   this.editDialogVisible=false
                   this.getUserList()
                   this.$message.success('数据更新成功')
         })
     },
     //根据id删除信息
      async removeUserById(id){
         //弹出是否删除
         const confirmResult= await this.$confirm('是否删除此文件', '提示', {
             confirmButtonText: '确定',
             cancelButtonText: '取消',
             type: 'warning'
         }).catch(err=>err) 
         if (confirmResult!=='confirm'){

             return this.$message('已经删除用户')
         }
         const {data:res}= await this.$http.delete('user'+id)

         if(res.mate.status!==200){
             return this.$message.error('删除失败')
         }
         this.$message.success('删除成功')
         //更新数据
         this.getUserList();
         }
}
  
}
</script>
<style lang="less" scoped>

</style>